package de.fhaugsburg.games.boardgames.scrabble.io;



import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

public class TerminalServer {

	
	
	
	private List<Integer> terminals;
	
	public TerminalServer(){
		terminals = new Vector<Integer>();
		terminals.add(1);
		terminals.add(2);
	}
	


	
	
	/**
	 * send message to a terminal
	 * @param msg
	 * @param id
	 */
	public void sendMessage(String msg, int id){
		File fTmp = new File(TerminalUtils.SERVER_MSG + id);
		try {
			TerminalUtils.writeFile(fTmp, msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * send message to a list of terminals
	 * @param msg
	 * @param terminalIds
	 */
	public void sendMessage(String msg, List<Integer> terminalIds){
		for (Integer id : terminalIds) {
			sendMessage(msg, id);
		}
	}
	
	
	
	/**
	 * sends message to all known/connected terminals
	 * @param msg
	 */
	public void sendMessageToAll(String msg){
		sendMessage(msg, terminals);
	}
	
	
	
	
	/**
	 * just write a request
	 * @param id
	 * @param request
	 */
	public void sendInputRequest(int id, String request){
		// write input request
		File reqFile = new File(TerminalUtils.INPUT_REQUEST + id);
		try {
			TerminalUtils.writeFile(reqFile, request);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	
	/**
	 * reads command from a terminal
	 * @param id
	 * @param request
	 * @return
	 * @throws InterruptedException 
	 */
	public String getInputLine(int id, String request) throws InterruptedException{
		
		sendInputRequest(id, request);
		
		
		
		// wait for input response, and read
		File fTmp = new File(TerminalUtils.INPUT_RESPONSE + id);
		while (!fTmp.exists()) {
			Thread.sleep(250);
		}
		
		// read input response
		try {
			// read
			String sTmp = TerminalUtils.readFile(fTmp);
			// delete 
			fTmp.delete();
			return sTmp;			
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	
	
	
	
	
	
	


	
	
	
}
